package com.tm.zuulserver.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TestFilter extends ZuulFilter {

    public static final String OPTIONS = "options";
    /**
     * 表示在什么时候进行拦截
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 表示filter执行的顺序，返回的值越小 优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE;
    }

    /**
     * 是否需要被拦截  retrun true表示需要被拦截
     * @return
     */
    @Override
    public boolean shouldFilter() {
        /**
         * 判断请求方式是否是options如果是 返回true，进行跨域拦截的校验
         */
        RequestContext currentContext = RequestContext.getCurrentContext();
        String methods = currentContext.getRequest().getMethod().toString();
        if(OPTIONS.equalsIgnoreCase(methods)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 拦截的处理逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //进行跨域拦截的处理
        // 获取request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();

        // 这些是对请求头的匹配，网上有很多解释
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Methods","GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Allow-Headers","authorization, content-type");
        response.setHeader("Access-Control-Expose-Headers","X-forwared-port, X-forwarded-host");
        response.setHeader("Vary","Origin,Access-Control-Request-Method,Access-Control-Request-Headers");

        // 跨域请求一共会进行两次请求 先发送options 是否可以请求
        // 调试可发现一共拦截两次 第一次请求为options，第二次为正常的请求 eg：get请求

        // 第二次请求（非验证，eg：get请求不会进到上面的if） 会走到这里往下进行
        // 不需要token认证
        ctx.setSendZuulResponse(true); //对请求进行路由
        ctx.setResponseStatusCode(HttpStatus.OK.value());
        ctx.set("isSuccess", true);
        return null;
    }
}
